package com.cy.utils;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.util.ArrayList;
import java.util.List;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cy.entity.SysConfig;
import org.apache.poi.ss.formula.functions.T;

/**
 * @Author: chenyi
 * @Email: 228112142@qq.com
 * @Description:
 * @Date: 2017/9/10 10:34
 */
public class JsonUtil {
    private static final String DEFAULT_CHARSET_NAME = "UTF-8";

    public static <T> String serialize(T object) {
        return JSON.toJSONString(object);
    }

    public static <T> T deserialize(String string, Class<T> clz) {
        return JSON.parseObject(string, clz);
    }

    public static <T> T load(Path path, Class<T> clz) throws IOException {
        return deserialize(
                new String(Files.readAllBytes(path), DEFAULT_CHARSET_NAME), clz);
    }

    public static <T> void save(Path path, T object) throws IOException {
        if (Files.notExists(path.getParent())) {
            Files.createDirectories(path.getParent());
        }
        Files.write(path,
                serialize(object).getBytes(DEFAULT_CHARSET_NAME),
                StandardOpenOption.WRITE,
                StandardOpenOption.CREATE,
                StandardOpenOption.TRUNCATE_EXISTING);
    }
    /**
     * @Author: chenyi
     * @Description: list对象转json字符串
     * @Date: 2017/9/10  10:50
     */
    public String listToJson(List<T> T){
        return JSON.toJSON(T).toString();
    }

    public List<T> jsonToList(String json){
        return JSONObject.parseArray(json, T.class);
    }




    public static void main(String[] args) {
        SysConfig person1 = new SysConfig();
        person1.setCode("address");
        person1.setValue("amao");

        SysConfig person2 = new SysConfig();
        person2.setCode("address");
        person2.setValue("amao");

        List<SysConfig> list = new ArrayList<SysConfig>();
        list.add(person1);
        list.add(person2);
//        System.out.println(serialize(lp));
//        String json="[{\"code\":\"address\",\"value\":\"amao\"},{\"code\":\"address\",\"value\":\"amao\"}]";
        //list转换为json
        String str=JSON.toJSON(list).toString();
        System.out.println(serialize(str));
        //json转换为list
        List<SysConfig> list2 = JSONObject.parseArray(str, SysConfig.class);
        System.out.println(serialize(list2));
    }
}
